package com.lvy.hczn.front.business.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.system.domain.business.*;
import com.lvy.hczn.front.business.dto.Param;
import com.lvy.hczn.front.business.service.*;
import com.lvy.hczn.front.business.util.ResultUtil;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.service.WarehouseService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RequestMapping("/wcs/order/deliver/")
@RestController
@Slf4j
public class DeliveryOrderDetailController {

    @Autowired
    private DeliveryOrderDetailService deliveryOrderDetailService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private WarehousingEntryService warehousingEntryService;

    @ApiOperation(value = "采购入库取货单输入", notes = "采购入库取货单输入")
    @PostMapping("entryByDeliverCode")
    public ResultUtil entryByDeliverCode(@RequestBody Param param) {
        try {
            List<PurchaseOrderDetail> list = deliveryOrderDetailService.entryByDeliverCode(param);
            return ResultUtil.ok(list);
        } catch (Exception e) {
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                log.error("entryByDeliverCode异常:{}",e);
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "生成取货单", notes = "采购入库取货单输入")
    @PostMapping("generateDeliver")
    public ResultUtil generateDeliver(@RequestBody Map<String, Object> map) {
        try {
            //取货单生成方式为：平台配送，则整个采购单生成的取货单有配送人员看到
            //自己配送，则根据供应商所供物品生成取货单
            //一个取货单对应一个采购单还是多个采购单？
            Integer num = 7;
            if (map != null) {
                if (map.containsKey("numOfPerBox")) {
                    num = (Integer) map.get("numOfPerBox");
                }
            }
            List<PurchaseOrder> purchaseOrderList = purchaseOrderService.list(Wrappers.<PurchaseOrder>lambdaQuery().eq(PurchaseOrder::getDeliveryStatus, "0"));
            if (!purchaseOrderList.isEmpty()) {
                String warehouseCode = warehouseService.selectLocalWarehouseFront().getWarehouseCode();
                for (PurchaseOrder purchaseOrder : purchaseOrderList) {
                    List<PurchaseOrderDetail> list = purchaseOrderDetailService.list(Wrappers.<PurchaseOrderDetail>lambdaQuery().eq(PurchaseOrderDetail::getPurchaseOrderCode, purchaseOrder.getPurchaseOrderCode()));
                    DeliveryOrder deliveryOrder = new DeliveryOrder();
                    deliveryOrder.setDeliveryOrderCode("QHD" + IdUtil.getSnowflake().nextIdStr());
                    deliveryOrder.setWarehouseCode(warehouseCode);
                    deliveryOrder.setPurchaserId(purchaseOrder.getCreateBy());
                    deliveryOrder.setSupplierId(warehouseCode);
                    deliveryOrder.setStatus("0");
                    deliveryOrder.setType("0");
                    for (PurchaseOrderDetail detail : list) {
                        DeliveryOrderDetail deliveryOrderDetail = new DeliveryOrderDetail();
                        deliveryOrderDetail.setDeliveryOrderCode(deliveryOrder.getDeliveryOrderCode());
                        deliveryOrderDetail.setWarehouseCode(warehouseCode);
                        deliveryOrderDetail.setPurchaseOrderCode(detail.getPurchaseOrderCode());
                        deliveryOrderDetail.setSupplierCode(deliveryOrder.getSupplierId());
                        deliveryOrderDetail.setNumber(1);
                        deliveryOrderDetail.setStatus("1");
                        deliveryOrderDetail.setDeliveryTime(LocalDateTime.now());
                        deliveryOrderDetail.setDeliveryNumber(2);
                        for (int i = 0; i < detail.getPurchaseQuantity(); i++) {
                            WarehousingEntry warehousingEntry = new WarehousingEntry();
                            warehousingEntry.setEntryCode("RKD" + IdUtil.getSnowflake().nextIdStr());
                            warehousingEntry.setServiceCode(detail.getPurchaseOrderCode());
                            warehousingEntry.setServiceType(purchaseOrder.getServiceType());
                            if (detail.getSpuId().equals("23") || detail.getSpuId().equals("25")) {
                                warehousingEntry.setHeight(BigDecimal.valueOf(220));
                                warehousingEntry.setWidth(BigDecimal.valueOf(65));
                                warehousingEntry.setLength(BigDecimal.valueOf(65));
                            } else {
                                warehousingEntry.setHeight(BigDecimal.valueOf(230));
                                warehousingEntry.setWidth(BigDecimal.valueOf(65));
                                warehousingEntry.setLength(BigDecimal.valueOf(65));
                            }
                            warehousingEntry.setNumberOfPerBox(num);
                            warehousingEntry.setSpuId(detail.getSpuId());
                            warehousingEntry.setSpecCode(detail.getSpecCode());
                            warehousingEntry.setPrice(BigDecimal.ONE);
                            warehousingEntry.setQuantity(1);
                            warehousingEntry.setWeight(detail.getWeight());
                            warehousingEntry.setPurchaserId(warehouseCode);
                            warehousingEntry.setUnit(detail.getUnit());
                            warehousingEntry.setSupplierCode(warehouseCode);
                            warehousingEntry.setProducerId(warehouseCode);
                            warehousingEntry.setShelfLife(detail.getProduceDate().plusDays(detail.getWarrantyDate()));
                            warehousingEntry.setPickTime(LocalDateTime.now());
                            warehousingEntry.setBatchCode(detail.getBatchCode());
                            warehousingEntry.setProvenance("湖南省长沙市");
                            warehousingEntry.setStatus("0");
                            warehousingEntry.setNumberOfPerBox(detail.getNumberOfPerBox());
                            warehousingEntry.setWeightOfPerBox(detail.getWeightOfPerBox());
                            warehousingEntryService.save(warehousingEntry);
                        }
                        deliveryOrderDetailService.save(deliveryOrderDetail);
                    }
                    deliveryOrderService.save(deliveryOrder);
                    LambdaUpdateWrapper<PurchaseOrder> updateWrapper = new LambdaUpdateWrapper();
                    updateWrapper.eq(PurchaseOrder::getPurchaseOrderCode, purchaseOrder.getPurchaseOrderCode()).set(PurchaseOrder::getDeliveryStatus, "1");
                    purchaseOrderService.update(updateWrapper);
                }
            }
            return ResultUtil.ok();
        } catch (Exception e) {
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }
}
